import React, { useState, useEffect } from 'react'
import { View, Image, Button } from '@tarojs/components'
import { AtList, AtButton, AtModal, AtModalAction, AtModalContent, AtModalHeader } from "taro-ui"
import Taro from '@tarojs/taro'
import MD5 from 'MD5'

import useModel from 'flooks';
import store from '../../../stores/index'

import './index.less'
import "taro-ui/dist/style/components/list.scss";
import "taro-ui/dist/style/components/modal.scss";

import api from '../../../http/api'
const { nsAddOrder, nsPay, nsOrderPrepay, nsDeleteOrder } = api


export default (props: any) => {
  const info: any = Taro.getStorageSync('info')
  const telWX = info ? JSON.parse(info).userInfo.tel : '000'
  const wxinfo: any = Taro.getStorageSync('wxinfo')
  const loginId:any = info?JSON.parse(info).userInfo.loginId:0
  const { openid } = JSON.parse(wxinfo)
  const { nsOrderParams, nsOrderParamsChange } = useModel(store.nsOrderParams, ['nsOrderParams'])
  const [open, setOpen] = useState(false)

  const [prepay_id, setPrepay_id] = useState('')
  const [nsOrderId, setNsOrderId] = useState(0)


  const {
    nsBusinessId,
    nsTypeId,
    telType,
    price,
    infoList
  } = props

  // 号码段类型  type     1电信  2联通   3移动温泉 4移动咸安
  // 选号类型    telType  1移动  2联通   3电信  

  const {
    id,
    loginManageId,
    uSchoolId,
    numTotal,
    num,
    title,
    detail,
    url,
    src
  } = props.data
  const {
    name,
    studentNum,
    telInput,
    height,
    weight,
    size,
    tel,
    schoolType,
    postage,
    idCard,
  } = nsOrderParams

  const toPage = (path: any) => {
    Taro.switchTab({
      url: path
    })
  }
  const onShareAppMessage = (res: any) => {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: `新生专区详情`,
      path: `/pages/nsBusinessDetail/index?nsBusinessId=${nsBusinessId}&nsTypeId=${nsTypeId}$telType=${telType}&price=${price}&infoList=${infoList}`
    }
  }
  const ModalErr = () => {
    let isErr
    switch (parseInt(nsTypeId)) {
      case 1:
        isErr = name && studentNum && idCard && telInput && height && weight && size ? false : true
        break;
      case 2:
        isErr = name && studentNum && idCard && telInput && height && weight ? false : true
        break;
      case 3:
        if (parseInt(telType) < 3) {
          // 移动分校区
          isErr = name && studentNum && idCard && telInput && tel && schoolType && postage ? false : true
        } else {
          // 非移动  不分校区
          isErr = name && studentNum && idCard && telInput && tel && postage ? false : true
        }
        break;
      case 4:
        isErr = name && studentNum && idCard && telInput ? false : true
        break;
      default:
        break;
    }
    return isErr
  }

  // 下单
  const toOlder = (i: any) => {
    const params = {
      loginManageId, uSchoolId, nsTypeId, nsBusinessId, telWX, name, studentNum, telInput, height, weight, size, tel, telType, price, openid, schoolType,
      postage,loginId
    }
    if (ModalErr()) {
      Taro.showModal({
        title: '',
        content: '请填写完整信息'
      })
    } else {
      nsAddOrder(params).then((res1: any) => {
        if (res1.msg === '-1') {
          Taro.showModal({
            title: '提示',
            content: '该号码已经被选中，请重新选择',
          })
        } else {
          nsOrderPrepay({
            prepay_id: res1.data.prepay_id
          }).then((res2: any) => {
            setPrepay_id(res1.data.prepay_id)
            setNsOrderId(res2.data.id)
            setOpen(true)
          })
        }
      })
    }
  }

  const makeCode = n => {
    var num = "";
    for (var i = 0; i < n; i++) {
      num += Math.floor(Math.random() * 10)
    }
    return num + '';
  }
  // 支付
  const pay = () => {
    if (prepay_id) {
      const params: any = {
        appId: 'wx069bb9fd47eb702b',
        timeStamp: parseInt(new Date().getTime() / 1000 + '') + '',
        nonceStr: makeCode(30),
        package: prepay_id,
        signType: 'MD5',    //RSA
      }
      const str = `appId=${params.appId}&nonceStr=${params.nonceStr}&package=${params.package}&signType=${params.signType}&timeStamp=${params.timeStamp}&key=liuhu666liuhu666liuhu666liuhu666`
      const paySign = MD5(str)
      params.paySign = paySign
      Taro.requestPayment({
        ...params,
        success: function (res) {
          nsPay({
            uSchoolId,
            nsOrderId,
            nsBusinessId,
            tel,
            postage,
            name,
            studentNum,
            idCard,
            telInput,
            telWX
          }).then(_ => {
            setOpen(false)
            Taro.redirectTo({
              url: `/pages/nsOrder/index`
            })
          })
        },
        fail: function (res) {
          Taro.showToast({
            title: '支付失败,请重新尝试',
            icon: 'none'
          }).then(_ => {
            setOpen(false)
          })
        }
      })
    } else {
      Taro.showToast({
        title: 'prepay_id未生成，请等待生成后支付',
        icon: 'none'
      })
    }

  }

  // 取消订单
  const cancelOrder = () => {
    nsDeleteOrder({ nsOrderId }).then(_ => {
      setOpen(false)
    })
  }
  return (
    <View className='footer'>
      <View className='footerL'>
        <View className='ico' onClick={() => { toPage('/pages/index/index') }}>
          <Image className='img' src={IMGSRC + 'usy.png'}></Image>
          <View className='txt'>首页</View>
        </View>
        <View className='ico ico2'>
          <Button className='shareBtn' openType='share' onClick={onShareAppMessage} type='primary'>
            <Image className='img' src={IMGSRC + 'ufx.png'}></Image>
          </Button>
          <View className='txt'>分享</View>
        </View>
        <View className='ico' onClick={() => { toPage('/pages/my/index') }}>
          <Image className='img' src={IMGSRC + 'uwd.png'}></Image>
          <View className='txt'>我的</View>
        </View>
      </View>
      <View className='footerR'>
        <AtButton onClick={toOlder} className='getBtn' size='small'>立即抢购</AtButton>
      </View>
      <AtModal isOpened={open} closeOnClickOverlay={false} onClose={() => { setOpen(false) }}>
        <AtModalContent>
          <View className="pay">
            {
              parseInt(nsTypeId) === 3 ?
                <View className="telWrap">
                  {/* <View className="tel">您选择的服务商为：{parseInt(telType) === 1 ? '中国移动' : parseInt(telType) === 2 ? '中国联通' : '中国电信'}</View> */}
                  <View>你选择的电话号码为：{tel}</View>
                </View> : <View className="title">{title}</View>
            }
            <View className="price">￥{price}</View>
          </View>
        </AtModalContent>
        <AtModalAction>
          <Button onClick={() => { cancelOrder() }}>取消订单</Button>
          <Button onClick={() => { pay() }}>确定购买</Button>
        </AtModalAction>
      </AtModal>
    </View>
  )
}
